package com.gljx.web.service.impl;

import com.gljx.util.GetFid;
import com.gljx.util.GetFnumber;
import com.gljx.util.TimeFormat;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.CarRefuelEntryMapper;
import com.gljx.web.dao.CarRefuelMapper;
import com.gljx.web.dao.CommonDao;
import com.gljx.web.service.CarRefuelService;
import com.gljx.web.service.CarService;
import com.gljx.web.service.OilspecService;
import com.gljx.web.service.PersonService;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class CarRefuelServiceImpl extends CommonDao implements CarRefuelService {

    @Autowired
    private CarRefuelMapper carRefuelMapper;

    @Autowired
    private CarRefuelEntryMapper carRefuelEntryMapper;

    @Autowired
    CarService carService;

    @Autowired
    OilspecService oilspecService;

    @Autowired
    PersonService personService;

    @Autowired
    HttpSession session;

    @Override
    public Map<String, Object> selectPageCount(String psql) {
        // TODO Auto-generated method stub
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("Psql", psql);
        paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
        this.getSqlSession().select("com.gljx.web.dao.CarRefuelMapper.pagecount", paramMap, null);
        return paramMap;
    }

    @Override
    public Map<String, Object> selectPage(int pindex, String psql, int psize) {
        // TODO Auto-generated method stub
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("Pindex", pindex);
        paramMap.put("Psql", psql);
        paramMap.put("Psize", psize);
        paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
        paramMap.put("v_cur", oracle.jdbc.OracleTypes.CURSOR);
        this.getSqlSession().select("com.gljx.web.dao.CarRefuelMapper.pagemap", paramMap, null);
        return paramMap;
    }

    @Override
    public String selectFnumber(String fnuber) {
        // TODO Auto-generated method stub
        return carRefuelMapper.selectFnumber(fnuber);
    }

    @Override
    public int addCarRefuel(CarRefuel carRefuel, String[] carId, String[] fseq, String[] cfcartype, String[] cftrainid,
                            String[] cfteamid, String[] cfgroupid, String[] cfkemu, String[] cfqty, String[] cfoilspecid,
                            String[] cfdesc, String[] cfdepname) {
        // TODO Auto-generated method stub
        int row1 = 0;
        int row2 = 0;
        //添加父类表
        row1 = carRefuelMapper.insertSelective(carRefuel);
        //添加子类
        for (int i = 0; i < carId.length; i++) {
            CarRefuelEntry carRefuelEntry = new CarRefuelEntry();
            carRefuelEntry.setFid(GetFid.UUIDIntoFid());
            carRefuelEntry.setFparentid(carRefuel.getFid());
            carRefuelEntry.setFseq(Long.valueOf(fseq[i]));
            carRefuelEntry.setCftrainid(cftrainid[i]);
            carRefuelEntry.setCfcarnoid(carId[i]);
            carRefuelEntry.setCfcartype(cfcartype[i]);
            carRefuelEntry.setCfqty(new BigDecimal(cfqty[i]));
            carRefuelEntry.setCfoilspecid(cfoilspecid[i]);
            carRefuelEntry.setCfdesc(cfdesc[i]);
            carRefuelEntry.setCfteamcoach(cfteamid[i]);
            carRefuelEntry.setCfgroupid(cfgroupid[i]);
            carRefuelEntry.setCfkemu(Long.valueOf(cfkemu[i]));
            carRefuelEntry.setCfdepname(cfdepname[i]);
            row2 += carRefuelEntryMapper.insertSelective(carRefuelEntry);
        }
        if (row1 > 0 && row2 > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public int deleteCarRefuelByFid(String fid) {
        // TODO Auto-generated method stub
        return carRefuelMapper.deleteByPrimaryKey(fid);
    }

    @Override
    public CarRefuel selCarRefuelByFid(String fid) {
        // TODO Auto-generated method stub
        return carRefuelMapper.selCarRefuelByFid(fid);
    }

    @Override
    public int updateCarRefuelByFid(CarRefuel carRefuel) {
        // TODO Auto-generated method stub
        return carRefuelMapper.updateByPrimaryKeySelective(carRefuel);
    }

    @Override
    public int updateCarRefuel(CarRefuel carRefuel, String[] carId, String[] fseq, String[] cfcartype,
                               String[] cftrainid, String[] cfteamid, String[] cfgroupid, String[] cfkemu, String[] cfqty,
                               String[] cfoilspecid, String[] cfdesc, String[] cfdepname) {
        // TODO Auto-generated method stub
        //删除子类
        carRefuelEntryMapper.deleteByParetnId(carRefuel.getFid());
        //修改父类
        int row1 = carRefuelMapper.updateByPrimaryKeySelective(carRefuel);
        //添加子类
        int row2 = 0;
        for (int i = 0; i < carId.length; i++) {
            CarRefuelEntry carRefuelEntry = new CarRefuelEntry();
            carRefuelEntry.setFid(GetFid.UUIDIntoFid());
            carRefuelEntry.setFparentid(carRefuel.getFid());
            carRefuelEntry.setFseq(Long.parseLong(fseq[i]));
            if(cftrainid[i]!=null){
            carRefuelEntry.setCftrainid(cftrainid[i]);//教练id
            }
            carRefuelEntry.setCfcarnoid(carId[i]);
            carRefuelEntry.setCfcartype(cfcartype[i]);
            carRefuelEntry.setCfqty(new BigDecimal(cfqty[i]));
            carRefuelEntry.setCfoilspecid(cfoilspecid[i]);
            carRefuelEntry.setCfdesc(cfdesc[i]);
            carRefuelEntry.setCfteamcoach(cfteamid[i]);
            carRefuelEntry.setCfgroupid(cfgroupid[i]);
            carRefuelEntry.setCfkemu(Long.valueOf(cfkemu[i]));
            carRefuelEntry.setCfdepname(cfdepname[i]);
            row2 += carRefuelEntryMapper.insertSelective(carRefuelEntry);
        }
        if (row1 > 0 && row2 > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public List<CarRefuel> selectCarRefuel(String companyId, String fnumber, String fdescription, String carNumber, String beginTime, String endTime) {
        return carRefuelMapper.selectCarRefuel(companyId, fnumber, fdescription, carNumber, beginTime, endTime);
    }

    @Override
    public List<String> RefuelRegisterImportExcel(List<List<Object>> list, String fileName) {

        //获取操作人信息
        User user = (User) session.getAttribute("user");

        List<String> successList = new ArrayList();

        List<String> errorList = new ArrayList();

        boolean errstate = true;


        successList.add("error");
        errorList.add("error");


        int oil = fileName.indexOf("汽油");

        String year = String.valueOf(list.get(0).get(0)).substring(0, 4);

        String mon = String.valueOf(list.get(0).get(0)).substring(5, 6);
        if (mon.length() == 1) {
            mon = "0" + mon;
        }

        for (int i = 0; i < list.size(); i++) {
            List<Object> row = list.get(i);
            if (i > 3 && row.size() < 35) {
                break;
            }
            //车型/类别
            String carType = String.valueOf(row.get(1));
            //车号
            String carNumber = String.valueOf(row.get(2));
            //对车号进行修改,因为录入的数据会添加赣字因此只有作筛选
            String  carNewNumber="";
            if(carNumber.indexOf("赣")>=0&&carNumber.lastIndexOf("学")>=0){
                  carNewNumber= carNumber.substring(carNumber.indexOf("赣")+1,carNumber.lastIndexOf("学"));
            }else{
                  carNewNumber=carNumber;
            }
            //加油员的姓名
            String jyName = String.valueOf(list.get(1).get(4));
            String jyId = "";

            List personList = personService.selectPersonByName(jyName);

            if (personList.size() != 0){
                //加油员的id
                 jyId = ((Person)personList.get(0)).getFid();
            }
            List<Car> carList = carService.queryCarByFnumber(carNewNumber, user.getFcompanyid());

            List<Oilspec> oilList = new ArrayList<>();

            if (oil!=-1) {
                oilList = oilspecService.queryOilsperByFcontrolunitidAndFnameL2(user.getFcompanyid(), "93#");
            } else {
                oilList = oilspecService.queryOilsperByFcontrolunitidAndFnameL2(user.getFcompanyid(), "柴油");
            }
            //创建了一个CarRefuelEntry的集合，用于存储CarRefuelEntry
           List<CarRefuelEntry> carRefuelEntries=new ArrayList<>();
           List<CarRefuel> carRefuelList=new ArrayList<>();
            for (int j = 4; j < row.size(); j++) {

//                if ("合计".equals(row.get(0))) {
//                    successList.set(0, "success");
//                    if (errstate) {
//                        return successList;
//                    } else {
//                        return errorList;
//                    }
//                }

                //判断是否需要导入
                if (!"".equals(row.get(j)) && i >= 3 && j < 35) {


                    //格式化日期
                    String day = String.valueOf((j - 3));
                    if (day.length() == 1) {
                        day = "0" + day;
                    }
					/*System.out.println("i:"+i+"-j:"+j);
					System.out.println(day);*/

                    String date = year + "/" + mon + "/" + day;
                    //System.out.println("车辆："+car+"--日期：" + date + "--油：" + row.get(j));

                    //判断是否是重复导入 这个判断一定要加上公司id
                    if (judgeIsInsertion(carList.get(0).getFid(), date,user.getFcompanyid())) {
                        continue;
                    }
                    successList.add(new String("车辆：" + carNumber + "--日期：" + date + "--油：" + row.get(j)));
                    //判断 主表 是否存在
                    List<String> bo = carRefuelMapper.selectCarRefuelByDate(date,user.getFcompanyid());//一定要与公司id相关联

                    try {
                        if (bo.size() == 0) {
                            //插入主表
                            CarRefuel carRefuel = new CarRefuel();
                            CarRefuelEntry carRefuelEntry = new CarRefuelEntry();

                            carRefuel.setFid(GetFid.UUIDIntoFid());
                            carRefuel.setFnumber(GetFnumber.fnumbers("JY-"));
                            carRefuel.setFcreatorid(user.getFid());
                            carRefuel.setFcreatetime(TimeFormat.timeFormat(new Date()));
                            carRefuel.setFcontrolunitid(user.getFcompanyid());
                            carRefuel.setFbizdate(date);
                            carRefuel.setFauditorid(user.getFid());
                            carRefuel.setCfficompanyid(user.getFcompanyid());
                            carRefuel.setFcreatetime(TimeFormat.timeFormat(new Date()));
                            carRefuel.setCfbillstate(3L);
                            //加油员id
                            carRefuel.setCfjypersonid(jyId);
                            carRefuel.setCfjypersonName(jyName);
                            carRefuelList.add(carRefuel);//将加油主表放入到集合中
                            carRefuelMapper.insertSelective(carRefuel);

                            //插入字表
                            carRefuelEntry.setFid(GetFid.UUIDIntoFid());
                            carRefuelEntry.setFparentid(carRefuel.getFid());
                            //车型
                            carRefuelEntry.setCfcartype(carType);
                            //车辆
                            if (!carList.isEmpty()) {
                                carRefuelEntry.setCfcarnoid(carList.get(0).getFid());
                            }
                            String s = (String) row.get(j);
                            carRefuelEntry.setCfqty(new BigDecimal(StringUtils.isEmpty(s.trim()) ? "0" : s.trim()));
                            carRefuelEntry.setCfkemu(0L);
                            //汽油规格
                            carRefuelEntry.setCfoilspecid(oilList.isEmpty() ? "" : oilList.get(0).getFid());
                            carRefuelEntries.add(carRefuelEntry);
                            carRefuelEntryMapper.insertSelective(carRefuelEntry);

                        } else {
                            //插入子表
                            CarRefuelEntry carRefuelEntry = new CarRefuelEntry();

                            carRefuelEntry.setFid(GetFid.UUIDIntoFid());
                            carRefuelEntry.setFparentid(bo.get(0));
                            //车型
                            carRefuelEntry.setCfcartype(carType);
                            //车辆
                            if (!carList.isEmpty()) {
                                carRefuelEntry.setCfcarnoid(carList.get(0).getFid());
                            }
                            String s = (String) row.get(j);
                            carRefuelEntry.setCfqty(new BigDecimal(StringUtils.isEmpty(s.trim()) ? "0" : s.trim()));
                            carRefuelEntry.setCfkemu(0L);
                            //汽油规格
                            carRefuelEntry.setCfoilspecid(oilList.isEmpty() ? "" : oilList.get(0).getFid());

                            //将驾校加油的子表放入集合中
                            carRefuelEntries.add(carRefuelEntry);
                                carRefuelEntryMapper.insertSelective(carRefuelEntry);


                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        errstate = false;
                        errorList.add("车辆：" + carNumber + "--日期：" + date + "--油：" + row.get(j) + "<br>");
                    }

                }

            }

        }


        successList.set(0, "success");

        if (errstate) {

            return successList;
        } else {
            return errorList;
        }

    }

    @Override
    public List<CarRefuelEntry> selCarRefuelEntryBycarName(String carName) {
        return carRefuelEntryMapper.selCarRefuelEntryBycarName(carName);
    }

    /**
     * @Author lcx
     * @Date 2018/5/14 0014 下午 5:34
     * 判断 驾校车辆加油 单据 是否可以插入 数据库
     */

    //todo  之后 再写 判断 驾校车辆加油 单据 是否可以插入 数据库  搞定
    private boolean judgeIsInsertion(String cfcarnoid, String date,String companyId) {

        List<String> list = carRefuelMapper.selectCarRefuelEntry(date, cfcarnoid,companyId);

        return list.size() != 0;
    }


}
